package cn.edu.ctbu.datajpa.webapi;

import cn.edu.ctbu.datajpa.domain.Admin;
import cn.edu.ctbu.datajpa.domain.Student;
import cn.edu.ctbu.datajpa.domain.Teacher;
import cn.edu.ctbu.datajpa.service.AdminService;
import cn.edu.ctbu.datajpa.service.StudentService;
import cn.edu.ctbu.datajpa.service.TeacherService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;

@RestController
@RequestMapping("/webapi/login")
public class LoginRestController {

    @Autowired
    StudentService studentService;

    @Autowired
    TeacherService teacherService;

    @Autowired
    AdminService adminService;

    @GetMapping("/user")

    public int user(HttpServletRequest httprequest, String username,String password){
            //判断用户名和密码是否存在
            List<Student> students=studentService.findByNoAndPassword(username,password);
            List<Teacher> teachers=teacherService.findByTnoAndPassword(username,password);
            List<Admin> admins=adminService.findByNoAndPassword(username,password);
            if(students.size()>0){
                //如果存在，写入session
                HttpSession session=httprequest.getSession();
                session.setAttribute("userid",students.get(0).getId());
                session.setAttribute("user",students.get(0));
                return 1;
            }else if(teachers.size()>0){
                HttpSession session=httprequest.getSession();
                session.setAttribute("userid",teachers.get(0).getId());
                session.setAttribute("user",teachers.get(0));
                return 2;
            }else if(admins.size()>0){
                HttpSession session=httprequest.getSession();
                session.setAttribute("userid",admins.get(0).getId());
                session.setAttribute("user",admins.get(0));
                return 3;
            }else{
                return -1;
            }
        }
}